<?php

namespace App\Models\Steel;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class SteelType extends Model
{
    protected $table = 'steel_type';
    public $timestamps = false;
    protected $primaryKey = 'id';
    protected $guarded = ['_token'];

    /**
     *获取列表 
     */
    public static function getList(Request $request, $cpid, $status = 0, $isgetall = 0)
    {
        $query = self::with(['subtype' => function ($query) {
            $query->select(['id', 'cpid', 'type_no', 'type_name', 'status', 'pid']);
        }])->where(['cpid' => $cpid, 'pid' => 0])->orderBy('create_at', 'desc');
        if (in_array($status, [1, 2])) {
            $query->where('status', $status);
        }
        $type_no = $request->type_no;
        if ($type_no != '') {
            $query->where('type_no', 'like', '%' . $type_no . '%');
        }

        $type_name = $request->type_name;
        if ($type_name != '') {
            $query->where('type_name', 'like', '%' . $type_name . '%');
        }

        $pre_type = $request->pre_type;
        if ($pre_type != '') {
            $query->where('pre_type', $pre_type);
        }

        if ($isgetall == 0) {
            $limit = $request->limit ?? 10;
            $list = $query->select(['id', 'cpid', 'type_no', 'type_name', 'status', 'pid'])->paginate($limit)->toArray();
            return paginateDataToArray($list);
        } else {
            $list = $query->select(['id', 'cpid', 'type_no', 'type_name', 'status', 'pid'])->get()->toArray();

            return ['list' => $list];
        }
    }

    public function subtype()
    {
        return $this->hasMany(SteelType::class, 'pid', 'id');
    }
}
